import { ResManager } from "./custom/ResManager";
import Global from "./settings";


export function import_csv_layout(content : string) : Array<string> {
    let str = content.replace(/\r/g,"");
    let mapArr = str.split("\n");
    var array = new Array();
    for (let index = 0; index < mapArr.length; index++) {
        const element = mapArr[index];
        let arr = element.split(",");
        array[index] = arr;
    }
    return array
};

// 返回的是图片文件
export function import_folder(key) {
    let res = ResManager.getInstance().getRes()
    return res[key]
}

export function choice(dict) {

    let array = []
    for(let key in dict) {
        array.push(key)
    }

    let randomIndex = Math.floor(Math.random()*array.length)
    return dict[array[randomIndex]]

}

export function changeToList(dict) {
    let array = []
    for(let key in dict) {
        array.push(dict[key])
    }
    return array
}

// pygame的零点在左上角，createor的零点在中心点，y轴正数在上面，负数在下面
export function changePos(pos) {

    let x = - 3648 / 2 + pos[0]
    let y = 3200 / 2 - pos[1] 

    return [x, y]

}

export function addToGroups(image, groups) {
    for(let group of groups) {
        group.addSprite(image)
    }
}

export function getTime() {
    return new Date().getTime()
}

export function getDictKeyList(dict) {

    let arr = []
    for(let key in dict) {
        arr.push(key)
    }
    return arr
}

export function getDictValueList(dict) {

    let arr = []
    for(let key in dict) {
        arr.push(dict[key])
    }
    return arr
}

export function spritecollide(sprite : cc.Node, spriteList : cc.Node[]) {
    let arr = []

    let spriteBox = sprite.getBoundingBox()
    for(let sp of spriteList) {
        if(cc.Intersection.rectRect(spriteBox, sp.getBoundingBox())) {
            arr.push(sp)
        }
    }
    return arr
}

export function randomInt(number) {
    return Math.floor(Math.random()*number)
}

export function randomBetween(number1, number2) {
    let offest = Math.random()*(number2-number1)
    return Math.floor(offest + number1)
}

// 矩形扩大或缩小
export function rectInflate(rect : cc.Rect, changeWidth, changeHeight) {
    let x = rect.xMin + changeWidth/2
    let y = rect.yMin - changeHeight/2
    let width = rect.width + changeWidth
    let height =  rect.height + changeHeight
    return new cc.Rect(x, y, width, height)
}

export function getColorNode(width, height) {
    let node = new cc.Node();
    let texture = new cc.Texture2D();
    let spriteFrame = new cc.SpriteFrame();
    texture.initWithData(new Uint8Array([255,255,255,255]), cc.Texture2D.PixelFormat.RGBA8888, 1, 1);
    spriteFrame.setTexture(texture);
    spriteFrame.setRect(cc.rect(0, 0, width, height));
    node.addComponent(cc.Sprite).spriteFrame = spriteFrame;
    return node
}